﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ClassLibrary.ContactRetriever
{
    using Google.Contacts;
    using Google.GData.Client;
    using Google.GData.Contacts;
    using Google.GData.Extensions;
    using System.Net;
    using System.Collections.Specialized;
using System.Net.Mail;

    public class GoogleContactRetriever : IContactRetriever
    {
        
        static readonly string SCOPE_URL = "http://www.google.com/m8/feeds/";

        string _continueUrl = string.Empty, _appName = "/", _userName = string.Empty, _password = string.Empty;

        public GoogleContactRetriever(string appName, string userName, string password)
        {
            //_continueUrl = continueUrl;
            _appName = appName;
            _userName = userName;
            _password = password;
        }

        public string UserName { get { return _userName; } }


        #region IContactRetriever Members

        public List<MailAddress> RetrieveContact()
        {

            List<MailAddress> ret = new List<MailAddress>();
            GAuthSubRequestFactory authFactory = new GAuthSubRequestFactory("cp", _appName);
            RequestSettings rs = new RequestSettings(_appName, _userName, _password);
            ContactsRequest cr = new ContactsRequest(rs);
            
            try
            {
                Feed<Contact> f = cr.GetContacts();
                string name = string.Empty;
                foreach (Contact e in f.Entries)
                {
                    if (e.PrimaryEmail !=null && e.PrimaryEmail.Address!=string.Empty)
                    {
                        //KeyValuePair<string, string> tmp = new KeyValuePair<string, string>(e.Title, e.Emails[0].Address);
                        //if (!ret.Contains(tmp))
                        //{
                        //    ret.Add(tmp);
                        //}
                        ret.Add(new MailAddress(e.PrimaryEmail.Address, e.Title));
                    }
                }
            }
            catch {
                return null;
            }

            return ret;
        }

        #endregion
    }
}
